﻿package igz.fleaxy.air {
	import flash.desktop.NativeApplication;
	import flash.display.NativeWindow;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.InvokeEvent;
	import flash.events.MouseEvent;
	import com.greensock.TweenNano;
	import igz.fleaxy.Fleaxy;
	import igz.fleaxy.util.ObjectUtil;
	//import flash.desktop.InvokeEventReason;
	
	/**
	 * @author Intelygenz | www.intelygenz.com
	 */
	public class MainWindowManager {
		
		private var _MainStage : Stage;
		
		private var _Settings : Object;

		public function MainWindowManager( p_settings:Object=null ) {
			
			_Settings = {
				"showOnInvoke" : true
			};
			ObjectUtil.$Merge( p_settings, _Settings );

			NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, _NativeApplication_OnInvoke);
			
			_MainStage = Fleaxy.$Current.$Stage;
			_MainStage.addEventListener(Event.MOUSE_LEAVE, _Stage_OnMouseLeave);
		}
		
		private function _NativeApplication_OnInvoke(p_invokeEvent:InvokeEvent) : void {
			//if ( p_invokeEvent.reason == InvokeEventReason.LOGIN ) { // Esto esta disponible desde AIR 1.5.1, pero no lo reconoce a la hora de compilar
			if ( _Settings["showOnInvoke"] ) {
				$ShowApp();
			}
			//}
		}
	
		public function $CloseApp() : void {
			NativeApplication.nativeApplication.exit();
		}

		public function $StartMove() : void {
			_MainStage.nativeWindow.startMove();
		}

		public function $SwapVisibleApp () : void {
			if ( _MainStage.nativeWindow.visible ) {
				$HideApp();
			}
			else {
				$ShowApp();
			}
		}

		public function $ShowApp () : void {
			_MainStage.nativeWindow.visible = true;
			_MainStage.nativeWindow.alwaysInFront = true;
			_MainStage.nativeWindow.alwaysInFront = false;			
		}

		public function $HideApp () : void {
			_MainStage.nativeWindow.visible = false;
		}
		
		private function _Stage_OnMouseLeave ( p_event:Event ) : void {
			_MainStage.dispatchEvent( new MouseEvent( MouseEvent.MOUSE_UP ) );
		}

	}

}